package com.bml.architect.netty.heart;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartNettyServerHandler extends SimpleChannelInboundHandler<String> {

    private int readTimeCount = 0 ;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        if(msg.equals("heart Packet")){
            System.out.println("recive client hart Packet is ："+msg);
            ctx.writeAndFlush("ok");
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        String msg = "";
        switch (event.state()){
            case ALL_IDLE:
                msg = "读写空闲";
                break;
            case READER_IDLE:
                msg = "读空闲";
                readTimeCount ++;
                break;
            case WRITER_IDLE:
                msg = "写空闲";
                break;
        }
        if(!msg.equals("")){
            System.out.println(msg);
        }
        if(readTimeCount > 3){
            System.out.println("server 端读取空闲超过3次，关闭连接，释放资源");
            ctx.writeAndFlush("idle close");
            ctx.channel().close();
        }
    }
}
